#include "Ogre.h"
#include <float.h>


#include "Main/Logger.h"
#include "Graphics/MapBlock.h"
#include "Graphics/MapCellMirror.h"
#include "Graphics/MaterialAtlas.h"

#include "AsmCall.h"
using namespace Graphics;



MapCellMirrorList::MapCellMirrorList(DwarfFort::MapCellList *originals)
:mOriginals(originals)
{
	
	mMaxX = originals->getXSize();
	mMaxY = originals->getYSize();
	mMaxZ = originals->getZSize();
	
	this->mCells = new MapCellMirror***[mMaxX];
	for (unsigned int x = 0; x < mMaxX; x++)
	{
		this->mCells[x] = new MapCellMirror**[mMaxY];
		for (unsigned int y = 0; y < mMaxY; y++)
		{
			this->mCells[x][y] = new MapCellMirror*[mMaxZ];
			for (unsigned int z = 0; z < mMaxZ; z++)
			{
				DwarfFort::MapCell *cell = originals->getMapCell(x,y,z);
				if (cell)
				{
				  mCells[x][y][z] = new MapCellMirror(cell);
				}
				else
					mCells[x][y][z] = 0;
			}
		}
	}
	connectNeighbours();
}



MapCellMirrorList::~MapCellMirrorList()
{
	for (unsigned int x = 0; x < mMaxX; x++)
	{
		for (unsigned int y = 0; y < mMaxY; y++)
		{
			for (unsigned int z = 0; z < mMaxZ; z++)
			{
				if (mCells[x][y][z])
					delete mCells[x][y][z];
			}
			delete[] mCells[x][y];
		}
		delete[] mCells[x];
	}
	delete[] mCells;
}





void MapCellMirrorList::connectNeighbours()
{
	for (unsigned int x = 0; x < mMaxX; x++)
		for (unsigned int y = 0; y < mMaxY; y++)
			for (unsigned int z = 0; z < mMaxZ; z++)
			{
		/*		if (mCells[x][y][z])
					mCells[x][y][z]->linkNeighbours(this);*/
			}
	
}









MapCellMirror::MapCellMirror(DwarfFort::MapCell *cell)
		:mOriginal(cell)
{
	mX=(cell->start_x/16); 
	mY=(cell->start_y/16);
	mZ=(cell->start_z);
	mCrc = calcHash();	
}

DWORD MapCellMirror::calcHash()
{
	DWORD result = 0;
	/* Hash function adapted from http://www.azillionmonkeys.com/qed/hash.html
	   (c) Paul Hsieh 
	*/
	DWORD hash = 0, tmp;

    int len = sizeof(this->mOriginal->mBlocks) >> 2;
	unsigned short *data = mOriginal->mBlocks; 
    /* Main loop */
    for (;len > 0; len--) {
        hash  += *data;
        tmp    = (*(data+2) << 11) ^ hash;
        hash   = (hash << 16) ^ tmp;
        data  ++;
        hash  += hash >> 11;
    }

    /* Force "avalanching" of final 127 bits */
    hash ^= hash << 3;
    hash += hash >> 5;
    hash ^= hash << 4;
    hash += hash >> 17;
    hash ^= hash << 25;
    hash += hash >> 6;

    return hash;
}


MapCellMirror::~MapCellMirror()
{

}




